<?php

namespace App\Http\Controllers\v1;

use App\Models\Student;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

/**
 * 微信相关
 * Class WxController
 * @package App\Http\Controllers\v1
 */
class WxController extends Controller
{
    /**
     * 微信请求登录，发送code
     * @param Request $request
     * @return array
     */
    public function code2Session(Request $request)
    {
//        登录时获取的 code
        $js_code = $request->get('js_code');
        if (empty($js_code)) return ['errcode' => 1, 'errmsg' => '参数错误'];
        $surl = config('wx.url.code2Session');
//        拼接数据
        $url = sprintf($surl, config('wx.openid'), config('wx.secret'), $js_code);
        $res = curl_request($url);
        /**
         * {
         * "session_key": "OOJyBnE3BFa0ESkCl6KDpA==",
         * "openid": "oUq_64nDTRWXADYQrU2tuSRlIXw8"
         * }
         */
        $data = json_decode($res, true);
//        获取失败
        if (!isset($data['openid'])) {
            return ['errcode' => $data['errcode'], 'errmsg' => $data['errmsg']];
        }

//        入库
        $openid = $data['openid'];
        $session_key = $data['session_key'];
        $id = Student::where('openid', $openid)->value('id');
        if ($id > 0) {
            Student::where('id', $id)->update(['session_key' => $session_key]);
        } else {
            $id = Student::create(['openid' => $openid, 'session_key' => $session_key])['id'];
        }
        return ['errcode' => 0, 'errmsg' => '登陆成功', 'loginSessionKey' => $id];
    }

    /**
     * post提交用户信息
     * @param Request $request
     * @return array
     */
    public function userinfo(Request $request)
    {
//        用户id
        $loginSessionKey = $request->get('loginSessionKey');
        if (empty($loginSessionKey)) return ['errcode' => 1, 'errmsg' => 'loginSessionKey不存在'];
        $data = [];
        $request->get('nickName') && $data['nickname'] = $request->get('nickName');
        $request->get('gender') && $data['gender'] = $request->get('gender') . '';
        $request->get('city') && $data['city'] = $request->get('city');
        $request->get('province') && $data['province'] = $request->get('province');
        $request->get('country') && $data['country'] = $request->get('country');
        $request->get('avatarUrl') && $data['avatar'] = $request->get('avatarUrl');
        /*$sql = 'UPDATE `la01_students` SET ';
        foreach ($data as $key=> $datum) {
            $sql .= "$key = '$datum' ,";
        }
        $sql = rtrim($sql,','). ' WHERE id='.$loginSessionKey;
        $res = DB::update($sql);
        echo $sql;
        dd($res);*/

        $data = Student::where('id', $loginSessionKey)->update($data);
//        return $data ? ['errcode' => 0, 'errmsg' => '用户信息录入成功'] : ['errcode' => 1, 'errmsg' => '用户信息录入失败'];
        return ['errcode' => 0, 'errmsg' => '用户信息录入成功'];
    }
}
